/**
 * 带动画的折线图组件（支持大数据渲染优化）
 */
import React, { useMemo } from 'react';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

interface DataPoint {
  date: string;
  [key: string]: string | number;
}

interface AnimatedLineChartProps {
  data: DataPoint[];
  lines: Array<{
    dataKey: string;
    name: string;
    color: string;
    strokeWidth?: number;
  }>;
  height?: number;
  showGrid?: boolean;
  showAnimation?: boolean;
}

const AnimatedLineChart: React.FC<AnimatedLineChartProps> = ({
  data,
  lines,
  height = 300,
  showGrid = true,
  showAnimation = true,
}) => {
  // 大数据优化：如果数据点超过1000个，进行采样
  const optimizedData = useMemo(() => {
    if (data.length <= 1000) return data;
    
    // 采样策略：保留首尾，中间均匀采样
    const sampleSize = 1000;
    const step = Math.floor(data.length / sampleSize);
    const sampled: DataPoint[] = [];
    
    for (let i = 0; i < data.length; i += step) {
      sampled.push(data[i]);
    }
    
    // 确保包含最后一个数据点
    if (sampled[sampled.length - 1] !== data[data.length - 1]) {
      sampled.push(data[data.length - 1]);
    }
    
    return sampled;
  }, [data]);

  // 检测是否需要双Y轴（当有销售额和订单数时，数值差距大，需要双Y轴）
  const needsDualYAxis = useMemo(() => {
    if (lines.length < 2) return false;
    if (optimizedData.length === 0) return false;
    
    // 检查是否有sales和orders字段，且数值差距大
    const hasSales = lines.some(line => line.dataKey === 'sales');
    const hasOrders = lines.some(line => line.dataKey === 'orders');
    
    if (hasSales && hasOrders) {
      // 计算销售额和订单数的最大值
      const maxSales = Math.max(...optimizedData.map(d => Number(d.sales) || 0));
      const maxOrders = Math.max(...optimizedData.map(d => Number(d.orders) || 0));
      
      // 如果最大值差距超过10倍，使用双Y轴
      return maxSales > 0 && maxOrders > 0 && (maxSales / maxOrders > 10 || maxOrders / maxSales > 10);
    }
    
    return false;
  }, [lines, optimizedData]);

  return (
    <ResponsiveContainer width="100%" height={height}>
      <LineChart
        data={optimizedData}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        {showGrid && <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />}
        <XAxis
          dataKey="date"
          tickFormatter={(value) => {
            const date = new Date(value);
            return `${date.getMonth() + 1}/${date.getDate()}`;
          }}
          stroke="#6b7280"
          style={{ fontSize: '12px' }}
        />
        {/* 左Y轴：用于销售额 */}
        <YAxis 
          yAxisId="left"
          stroke="#6b7280" 
          style={{ fontSize: '12px' }}
          label={needsDualYAxis ? { value: '销售额(元)', angle: -90, position: 'insideLeft' } : undefined}
        />
        {/* 右Y轴：用于订单数（当需要双Y轴时） */}
        {needsDualYAxis && (
          <YAxis 
            yAxisId="right"
            orientation="right"
            stroke="#10b981" 
            style={{ fontSize: '12px' }}
            label={{ value: '订单数(单)', angle: 90, position: 'insideRight' }}
          />
        )}
        <Tooltip
          contentStyle={{
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            border: '1px solid #e5e7eb',
            borderRadius: '8px',
            padding: '8px 12px',
          }}
          labelFormatter={(value) => {
            const date = new Date(value);
            return date.toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: 'long',
              day: 'numeric',
            });
          }}
          formatter={(
            value: number,
            name: string,
            props: { payload?: { sales?: number; orders?: number } }
          ) => {
            const payload = props?.payload;
            const salesValue = typeof payload?.sales === 'number' ? payload.sales : undefined;
            const ordersValue = typeof payload?.orders === 'number' ? payload.orders : undefined;
            const hasSales = typeof salesValue === 'number';
            const hasOrders = typeof ordersValue === 'number' && ordersValue > 0;

            // 当同时有销售额和订单数时，在 tooltip 最后一行额外显示客单价
            if (name === '销售额(元)' && hasSales && hasOrders && salesValue !== undefined && ordersValue) {
              const avg = (salesValue / ordersValue).toFixed(2);
              return [`${value.toLocaleString()} (客单价 ¥${avg})`, name];
            }

            return [
              typeof value === 'number' ? value.toLocaleString() : value,
              name,
            ];
          }}
        />
        <Legend />
        {lines.map((line, index) => {
          // 如果是订单数且需要双Y轴，使用右Y轴
          const yAxisId = (needsDualYAxis && line.dataKey === 'orders') ? 'right' : 'left';
          return (
            <Line
              key={line.dataKey}
              yAxisId={yAxisId}
              type="monotone"
              dataKey={line.dataKey}
              name={line.name}
              stroke={line.color}
              strokeWidth={line.strokeWidth || 2}
              dot={{ r: 4 }}
              activeDot={{ r: 6 }}
              isAnimationActive={showAnimation}
              animationDuration={800 + index * 100}
              animationEasing="ease-out"
            />
          );
        })}
      </LineChart>
    </ResponsiveContainer>
  );
};

export default AnimatedLineChart;
